const express = require('express')
const {
  check
} = require('express-validator')
const {
  validate
} = require('../utils/validate')

const controller = require('../controllers/user')

const {
  uploadAvatar
} = require('../utils/upload')

const {
  validateToken
} = require('../utils/user')
const router = express.Router()

router.route('/users')
  .post(validate([
    check('username').isString().withMessage('username  必须是字符串类型'),
    check('password').isString().isLength({
      min: 6
    }).withMessage('password 长度必须大于6'),
    check().custom(body => {
      const keys = ['username', 'password']
      return Object.keys(body).every(key => keys.includes(key))
    }).withMessage('参数只能包含username, password')
  ]), controller.create)
  .get(
    validate([
      check('admin').optional().isString().withMessage('search 必须是字符串类型'),
      check('page').optional().isInt().withMessage('page 必须是数值类型'),
      check('pagesize').optional().isInt().withMessage('pagesize 必须是数值类型'),
      check().custom(body => {
        const keys = ['admin', 'page', 'pagesize']
        return Object.keys(body).every(key => keys.includes(key))
      }).withMessage('参数只能包含admin, page, pagesize')
    ]),
    controller.index)

router.route('/users/:id')
  .get(controller.show)
  .put(
    validate([
      check('oldPassword').optional().isString().withMessage('search 必须是字符串类型'),
      check('newPassword').optional().isString().withMessage('search 必须是字符串类型'),
      check().custom(body => {
        const keys = ['avatar', 'oldPassword', 'newPassword']
        return Object.keys(body).every(key => keys.includes(key))
      }).withMessage('参数只能包含avatar, oldPassword, newPassword')
    ]),
    uploadAvatar.single('avatar'), controller.update)
  .delete(controller.delete)

module.exports = router
